package com.xzh.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {
/*    @Autowired*/
    RabbitTemplate rabbitTemplate;

    @Primary
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate=rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageConverter());
        initRabbitTemplate();
        return rabbitTemplate;
    }


    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    //定制RabbitTemplate
   // @PostConstruct //MyRabbitConfig对象创建完之后，执行这个方法
    public void initRabbitTemplate(){
        //设置确认回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {

            /*1、只要消息抵达Broker,就cak = true，
            correlationData 当前消息的唯一关联数据，包含消息的唯一id
            ack  消息是否成功收到
            cause 失败的原因
            * */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("confirm...correlationData【"+correlationData+"】==>ack【"+ack+"】==>cause【"
                +cause+"】");

            }
        });

        //设置消息抵达队列的回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /*只要消息没有投递给指定的队列就会触发这个失败的回调
            * message 投递失败的消息
            * replyCode 回复的状态码
            * replyText 回复的内容
            * exchange 当时这个消息是发给哪个交换机
            * routingKey 这个消息所使用的路由键
            * */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("fail Message["+message+"]===>replyCode["+replyCode+"]===>replyText["+replyText
                +"]===>exchange["+exchange+"]===>routingkey["+routingKey+"]");
            }
        });
    }
}
